package controller.main
{
	import events.main.EventBrowseForFiles;
	
	import flash.filesystem.File;
	import flash.utils.ByteArray;
	
	import model.ModelBrowseFile;
	import model.ModelLibrary;
	import model.ModelProject;
	import model.ModelRooms;
	
	import org.flashIso.engine.base.IsoRoom;
	import org.flashIso.engine.library.objects.LBinaryData;
	import org.flashIso.engine.library.objects.LImage;
	import org.robotlegs.mvcs.Command;
	
	import others.EditorIsoFactory;
	
	import services.IServiceFile;
	
	public class CommandSaveProject extends Command
	{
		[Inject]
		public var mp:ModelProject;

		[Inject]
		public var mb:ModelBrowseFile;
		
		[Inject]
		public var ml:ModelLibrary;
		
		[Inject]
		public var mr:ModelRooms;
		
		[Inject]
		public var fs:IServiceFile;
		
		override public function execute() : void {
			if (mp.projectFilePath == null){
				dispatch(new EventBrowseForFiles(EventBrowseForFiles.BROWSE_FOR_FILES, mb.BROWSE_FOR_SAVE_PROJECT));
			}else{
				var i:uint;
				var xml:XML = <Data/>;
				xml.appendChild(ml.toXML());
				xml.appendChild(mr.toXML());
				
				var data:ByteArray = new ByteArray();
				data.writeUTFBytes(xml.toXMLString());
				fs.writeFile(mp.projectFilePath, data, (mb.projectExtension[1] as String).substr(2));
				
				
				//write images
				var file:File = new File(mp.projectFilePath).parent.resolvePath("images");
				if (file.exists){
					file.deleteDirectory(true);
				}
				if (ml.imagesDataProvider.length > 0) {
					file.createDirectory();	
					for (i = 0; i < ml.imagesDataProvider.length; i++){
						var imageFile:File = file.resolvePath((ml.imagesDataProvider[i] as LImage).id);
						if (imageFile.exists){
							imageFile.deleteFile();
						}
						fs.writeFile(imageFile.nativePath, (ml.imagesDataProvider[i] as LImage).data);
					}
				}
					
				
				//write binaries
				file = new File(mp.projectFilePath).parent.resolvePath("binaries");
				if (file.exists){
					file.deleteDirectory(true);
				}
				if (ml.binaryDataProvider.length > 0) {
					file.createDirectory();	
					for (i = 0; i < ml.binaryDataProvider.length; i++){
						var binaryFile:File = file.resolvePath((ml.binaryDataProvider[i] as LBinaryData).id);
						if (binaryFile.exists){
							binaryFile.deleteFile();
						}
						fs.writeFile(binaryFile.nativePath, (ml.binaryDataProvider[i] as LBinaryData).data);
					}
				}
				mp.projectModified = false;
			}
		}
		
	}
}